package com.rtf.framework.dao.rule.unique;

import com.rtf.framework.common.exception.AppException;
import com.rtf.framework.common.support.dao.handler.AppBaseDataHandlerAdaptor;
import com.rtf.framework.common.util.UtilString;
import org.springframework.beans.factory.annotation.Autowired;

import javax.persistence.Table;
import java.util.Collection;

public class UniqueCodeDataHandler extends AppBaseDataHandlerAdaptor {

    @Autowired
    private UniqueCodeRecordDao uniqueCodeRecordDao;

    @Override
    public boolean support(Class<?> entityClass) {
        return UniqueCodeRecord.class.isAssignableFrom(entityClass);
    }

    @Override
    public <T> T preSaveHandler(T entity) {
        Table tableAnno = entity.getClass().getAnnotation(Table.class);
        if (tableAnno == null) {
            throw new AppException("当前类必须是jpa管理的类");
        }
        UniqueCodeRecord uniqueCodeRecord = (UniqueCodeRecord) entity;
        if (UtilString.isBlank(uniqueCodeRecord.getCode())) {
            throw new AppException("编码不能为空");
        }

        //将编码统一去除空字符，并进行裁剪
        uniqueCodeRecord.setCode(uniqueCodeRecord.getCode().trim().toLowerCase());

        int existNum = uniqueCodeRecordDao.queryExistCount(tableAnno.name(), uniqueCodeRecord.getCode(), null);
        if (existNum > 0) {
            throw new AppException("保存失败，已经存在相同标识的记录。");
        }

        return super.preSaveHandler(entity);
    }

    @Override
    public <T> T preUpdateHandler(T entity, Collection<String> updateFields) {
        Table tableAnno = entity.getClass().getAnnotation(Table.class);
        if (tableAnno == null) {
            throw new AppException("当前类必须是jpa管理的类");
        }

        UniqueCodeRecord uniqueCodeRecord = (UniqueCodeRecord) entity;

        if (UtilString.isNotBlank(uniqueCodeRecord.getCode())) {
            //将编码统一去除空字符，并进行裁剪
            uniqueCodeRecord.setCode(uniqueCodeRecord.getCode().trim().toLowerCase());
            int existNum = uniqueCodeRecordDao.queryExistCount(tableAnno.name(), uniqueCodeRecord.getCode(), uniqueCodeRecord.getId());
            if (existNum > 0) {
                throw new AppException("更新失败，已经存在相同标识的记录。");
            }
        }

        return super.preUpdateHandler(entity, updateFields);
    }

}
